package com.aidex.biz.service.impl;

import com.aidex.biz.domain.bo.HomeBo;
import com.aidex.biz.domain.bo.HomeDataBoxBo;
import com.aidex.biz.domain.bo.HomeKuaiJieDataBo;
import com.aidex.biz.domain.bo.HomeShortDataBo;
import com.aidex.biz.mapper.HomeMapper;
import com.aidex.biz.service.HomeService;
import com.aidex.biz.utils.DateRangeUtil;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.domain.entity.SysDept;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.system.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class HomeServiceImpl implements HomeService {

    @Autowired(required = false)
    private HomeMapper mapper;

    @Autowired
    private SysDeptService sysDeptService;


    @DataScope(userAlias = "a", deptAlias = "a")
    @Override
    public HomeDataBoxBo getDataBoxInfo(HomeBo homeBo) {
        return mapper.getDataBoxInfo(homeBo);
    }

    @DataScope(userAlias = "a", deptAlias = "a")
    @Override
    public HomeShortDataBo getShortDataInfo(HomeBo homeBo) {
        homeBo = getDateStats(homeBo);
        if (StringUtils.isNotNull(homeBo.getDeptId()) && StringUtils.isNotEmpty(homeBo.getDeptId())) {
            List<SysDept> sysDeptList = sysDeptService.selectChildrenDeptById(homeBo.getDeptId());

            String[] deptIds = sysDeptList.stream().map(SysDept::getId).toArray(String[]::new);
            homeBo.setDeptIds(deptIds);
        }
        return this.getAllShortDataInfo(homeBo);
    }


    /**
     * 应用程序层面处理 分多条sql查询 再合并结果集 增加查询速率
     *
     * @param homeBo
     * @return
     */
    private HomeShortDataBo getAllShortDataInfo(HomeBo homeBo) {

        HomeShortDataBo shortDataInfoXs = mapper.getShortDataInfoXs(homeBo);
        HomeShortDataBo shortDataInfoKh = mapper.getShortDataInfoKh(homeBo);
        HomeShortDataBo shortDataInfoGj = mapper.getShortDataInfoGj(homeBo);
        HomeShortDataBo shortDataInfoSm = mapper.getShortDataInfoSm(homeBo);
        HomeShortDataBo shortDataInfoQd = mapper.getShortDataInfoQd(homeBo);
        HomeShortDataBo shortDataInfoJj = mapper.getShortDataInfoJj(homeBo);
        HomeShortDataBo shortDataInfoFk = mapper.getShortDataInfoFk(homeBo);
        HomeShortDataBo shortDataInfoHk = mapper.getShortDataInfoHk(homeBo);

        HomeShortDataBo homeShortDataBo = new HomeShortDataBo();
        homeShortDataBo.setSdXs(shortDataInfoXs.getSdXs());
        homeShortDataBo.setSdKh(shortDataInfoKh.getSdKh());
        homeShortDataBo.setSdJt(shortDataInfoGj.getSdJt());
        homeShortDataBo.setSdGj(shortDataInfoGj.getSdGj());
        homeShortDataBo.setSdSm(shortDataInfoSm.getSdSm());
        homeShortDataBo.setSdQd(shortDataInfoQd.getSdQd());
        homeShortDataBo.setSdZc(shortDataInfoXs.getSdZc());
        homeShortDataBo.setSdJj(shortDataInfoJj.getSdJj());
        homeShortDataBo.setSdFk(shortDataInfoFk.getSdFk());
        homeShortDataBo.setSdFkAmount(shortDataInfoFk.getSdFkAmount());
        homeShortDataBo.setSdHk(shortDataInfoHk.getSdHk());
        homeShortDataBo.setSdHkAmount(shortDataInfoHk.getSdHkAmount());
        return homeShortDataBo;
    }

    @Override
    public List<Map<String, Object>> indexPaiHangBangSelf(HomeBo homeBo) {

        homeBo = getDateStats(homeBo);
        homeBo.setUserId(SecurityUtils.getUserId());

        List<Map<String, Object>> allUsers = mapper.indexPaiHangBangSelf(homeBo);
        // 取前10条（如果不足10条，则取全部）
        List<Map<String, Object>> top10Users = allUsers.subList(0, Math.min(10, allUsers.size()));
        boolean hasCurrentUser = false;
        String targetUserId = SecurityUtils.getUserId(); // 你要查找的 userId

        for (Map<String, Object> user : top10Users) {
            if (targetUserId.equals(user.get("userId").toString())) {
                hasCurrentUser = true;
                break; // 找到后立即退出循环
            }
        }
        //如果不存在 就去找出当前用户
        if (!hasCurrentUser) {
            Map<String, Object> matchedUser = null;
            for (Map<String, Object> allUser : allUsers) {
                if (targetUserId.equals(allUser.get("userId").toString())) {
                    matchedUser = allUser;
                    break;  // 找到后立即退出循环
                }
            }
            if (null != matchedUser) {
                top10Users.add(matchedUser);
            }
        }
        return top10Users;
    }

    @Override
    public List<Map<String, Object>> indexPaiHangBangDept(HomeBo homeBo) {
        homeBo = getDateStats(homeBo);
        homeBo.setDeptId(SecurityUtils.getDeptId());

        List<Map<String, Object>> allDepts = mapper.indexPaiHangBangDept(homeBo);
        // 取前10条（如果不足10条，则取全部）
        List<Map<String, Object>> top10Depts = allDepts.subList(0, Math.min(10, allDepts.size()));
        boolean hasCurrentDept = false;
        String targetDeptId = SecurityUtils.getDeptId(); // 你要查找的 deptId
        for (Map<String, Object> dept : top10Depts) {
            if (targetDeptId.equals(dept.get("deptId").toString())) {
                hasCurrentDept = true;
                break; // 找到后立即退出循环
            }
        }
        //如果不存在 就去找出当前用户
        if (!hasCurrentDept) {
            Map<String, Object> matchedDept = null;
            for (Map<String, Object> allDept : allDepts) {
                if (targetDeptId.equals(allDept.get("deptId").toString())) {
                    matchedDept = allDept;
                    break;  // 找到后立即退出循环
                }
            }
            if (null != matchedDept) {
                top10Depts.add(matchedDept);
            }
        }
        return top10Depts;
    }

    @Override
    public HomeKuaiJieDataBo getKuaiJieDataInfo(HomeBo homeBo) {
        return mapper.getKuaiJieDataInfo(homeBo);
    }


    /**
     * 避免使用DATE_FORMAT函数（会使索引实效） 直接获取日期节点
     *
     * @param homeBo
     * @return
     */
    public HomeBo getDateStats(HomeBo homeBo) {

        //默认当月
        homeBo.setStartDate(DateRangeUtil.getMonthStart());
        homeBo.setEndDate(DateRangeUtil.getMonthEnd());

        if (StringUtils.isEmpty(homeBo.getDateRange())) {
            switch (homeBo.getDateText()) {
                case "toDay":
                    homeBo.setStartDate(DateRangeUtil.getTodayStart());
                    homeBo.setEndDate(DateRangeUtil.getTodayEnd());
                    break;
                case "yesterday":
                    homeBo.setStartDate(DateRangeUtil.getYesterdayStart());
                    homeBo.setEndDate(DateRangeUtil.getYesterdayEnd());
                    break;
                case "toWeek":
                    homeBo.setStartDate(DateRangeUtil.getWeekStart());
                    homeBo.setEndDate(DateRangeUtil.getWeekEnd());
                    break;
                case "lastMonth":
                    homeBo.setStartDate(DateRangeUtil.getLastMonthStart());
                    homeBo.setEndDate(DateRangeUtil.getLastMonthEnd());
                    break;
                case "toQuarter":
                    homeBo.setStartDate(DateRangeUtil.getQuarterStart());
                    homeBo.setEndDate(DateRangeUtil.getQuarterEnd());
                    break;
                case "lastQuarter":
                    homeBo.setStartDate(DateRangeUtil.getLastQuarterStart());
                    homeBo.setEndDate(DateRangeUtil.getLastQuarterEnd());
                    break;
                case "toYear":
                    homeBo.setStartDate(DateRangeUtil.getYearStart());
                    homeBo.setEndDate(DateRangeUtil.getYearEnd());
                    break;
                case "lastYear":
                    homeBo.setStartDate(DateRangeUtil.getLastYearStart());
                    homeBo.setEndDate(DateRangeUtil.getLastYearEnd());
                    break;
            }
        } else {
            if (homeBo.getDateRange().length == 2) {
                homeBo.setStartDate(homeBo.getDateRange()[0]);
                homeBo.setEndDate(homeBo.getDateRange()[1]);
            }

        }

        return homeBo;
    }

    public HomeBo indexBoSqlCombine(HomeBo homeBo) {
        String sql = "DATE_FORMAT(a.create_time,'%y%m') = DATE_FORMAT(now(),'%y%m')";//当前月
        if (StringUtils.isEmpty(homeBo.getDateRange())) {
            switch (homeBo.getDateText()) {
                case "toDay":
                    sql = "DATE(a.create_time) = CURDATE()";

                    break;
                case "yesterday":
                    sql = "DATE_FORMAT(a.create_time,'%y%m%d') = DATE_FORMAT(CURDATE() - INTERVAL 1 DAY,'%y%m%d')";

                    break;
                case "toWeek":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE()) AND WEEK(a.create_time) = WEEK(CURDATE())";

                    break;
                case "lastMonth":
                    sql = "DATE_FORMAT(a.create_time,'%y%m') = DATE_FORMAT(now(),'%y%m')-1";

                    break;
                case "toQuarter":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE()) and QUARTER(a.create_time) = QUARTER(CURRENT_DATE()) ";

                    break;
                case "lastQuarter":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE()) -1 and QUARTER(a.create_time) = QUARTER(CURRENT_DATE" +
                            "()) - 1";

                    break;
                case "toYear":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE())";

                    break;
                case "lastYear":
                    sql = "YEAR(a.create_time) = YEAR(CURDATE()) - 1";

                    break;
            }
        } else {
            if (homeBo.getDateRange().length == 2) {
                sql = "date_format(a.create_time,'%y%m%d') >= date_format('" + homeBo.getDateRange()[0] + "'," + "'%y" +
                        "%m" + "%d')" + "AND date_format(a.create_time,'%y%m%d') <= date_format('" + homeBo.getDateRange()[1] + "','%y%m%d')";
            }

        }
        homeBo.setSearchDateSql("and " + sql);
        return homeBo;
    }
}
